﻿using Furion.FriendlyException;
using GMS.NET.Const;
using GMS.NET.Core.Entitys.Excel.Basic;
using GMS.NET.Core.Entitys.System;
using GMS.NET.Core.Users;
using GMS.NET.Dto.System.Users.Shared;
using GMS.NET.Encrypt;
using GMS.NET.SqlSugarCore.DbCore;
using Mapster;

namespace GMS.NET.Application.Service.System.Users
{
    [Authorize]
    [DynamicApiController]
    public class UsersService : DbManger, IUsersService
    {
        private readonly IExcelService excelService = App.GetService<IExcelService>();
        public async Task DelUser([FromBody] List<Guid> Ids)
        {
            var userId = await MasterDb.Queryable<GMSNet_User>()
                   .Where(x => Ids.Contains(x.Id))
                   .Select(x => x.User_Account)
                   .ToListAsync();

            if (userId.Any(x => x == UserInfo.UserId))
                throw Oops.Bah("操作人不可删除操作人账号");
            await MasterDb.Deleteable<GMSNet_User>()
                .Where(x => Ids.Contains(x.Id))
                .ExecuteCommandAsync();
        }
        [HttpPost]
        public async Task<TabularData<UsersData>> GetUsers([FromBody] QueryPivot queryPivot)
        {
            var result = new List<UsersData>();
            RefAsync<int> Total = 0;
            if (queryPivot.IsPage)
            {
                result = await MasterDb.Queryable<GMSNet_User>()
                    .LeftJoin<GMSNet_Role>((x, y) => x.User_RoleId == y.Id)
                    .LeftJoin<GMSNet_Customer>((x, y, z) => x.User_CusId == z.Id)
                    .WhereIF(!UserInfo.UserAdmin, (x, y, z) => x.User_CusId == Guid.Parse(UserInfo.CusId))
                    .Select((x, y, z) => new UsersData
                    {
                        Id = x.Id,
                        User_RoleName = y.Role_Name,
                        User_CusName = z.Cust_Name
                    }, true)
                    .MergeTable()
                   .Where(queryPivot.WhereModel!.GetSearches())
                   .ToPageListAsync(queryPivot.PageIndex, queryPivot.PageSize, Total);
            }
            else
            {
                await MasterDb.Queryable<GMSNet_User>()
                     .WhereIF(!UserInfo.UserAdmin, x => x.User_CusId == Guid.Parse(UserInfo.CusId))
                    .ForEachAsync(it => result.Add(it.Adapt<UsersData>()), 200);
                Total = result.Count();
            }
            return new TabularData<UsersData> { Items = result, page_Total = Total };
        }
        public async Task<string> SaveUser([FromBody] UsersData usersData)
        {
            //Mapster自动映射
            var PramUser = usersData.Adapt<GMSNet_User>();
            if (PramUser.Id != Guid.Empty)
            {
                var OrgUser = await MasterDb.Queryable<GMSNet_User>().InSingleAsync(PramUser.Id);
                PramUser.Creationtime = OrgUser.Creationtime;
                PramUser.Creator = OrgUser.Creator;
                PramUser.User_PassWord = OrgUser.User_PassWord;
                await MasterDb.Updateable(PramUser)
                    .CallEntityMethod(it => it.SetUpdateUser())
                    .ExecuteCommandAsync();
                return string.Empty;
            }
            else
            {
                if (!UserInfo.UserAdmin) PramUser.User_CusId =Guid.Parse(UserInfo.CusId);
                //获取私钥
                var privateKey = App.Configuration.GetSection(EncryptConst.PrivateKey).Value ?? "";
                var PassWord = SHA.Hash512(RSA.Decrypt(usersData.CipherText!, privateKey));
                PramUser.User_PassWord = PassWord;
                PramUser.User_Remark = "";
                await MasterDb.Insertable(PramUser)
                    .CallEntityMethod(it => it.SetAddUser())
                    .ExecuteCommandAsync();
                return PassWord;
            }
        }
        [HttpPost]
        [NonUnify]
        public async Task<MemoryStream> GetExcelTemp()
        {
            var values = new List<DatabaseTemplate>()
            {
                new DatabaseTemplate()
                {
                           Descr="112",
               Example="31",
                IsNull="Y",
                Serialnumber=1,
                 Keyword="12",
                 Name="123",
                 Type="231"
                }
            };
            var Stream = await MiniExcelTool.GetExcelStreamAsync(values.ConvertGetExcelAttrToDictionaryList());
            return Stream;
        }
        public async Task UsersDataCheck()
        {
            await excelService.CheckData(async (arg) =>
            {
                var UserList = (await arg.QueryAsync<DatabaseTemplate>()).ToList();
                UserList.ForEach(x => { x.CheckMessage = "error"; x.CheckStatus = false; });
                return (UserList, false);
            });
        }
        public async Task UsersDataImport()
        {
            await excelService.ImportData(async (arg) =>
            {
                var UserList = (await arg.QueryAsync<DatabaseTemplate>()).ToList();

                return true;
            });
        }
        [HttpPost]
        public async Task<List<KeyValues>> GetRolesList([FromBody] string Text)
        {
            var result = await MasterDb.Queryable<GMSNet_Role>()
                .WhereIF(!UserInfo.UserAdmin, x => x.Id == Guid.Parse(UserInfo.RoleId))
                .WhereIF(!string.IsNullOrWhiteSpace(Text), x => x.Role_Name!.Contains(Text))
                .Select(x => new KeyValues()
                {
                    Key = x.Role_Name,
                    Value = x.Id
                })
                .ToListAsync();
            return result;
        }
        [HttpPost]
        public async Task<List<KeyValues>> GetCustsList([FromBody] string Text)
        {
            var result = await MasterDb.Queryable<GMSNet_Customer>()
                 .WhereIF(!UserInfo.UserAdmin, x => x.Id == Guid.Parse(UserInfo.CusId))
                 .WhereIF(!string.IsNullOrWhiteSpace(Text), x => x.Cust_FullName!.Contains(Text))
                    .Select(x => new KeyValues()
                    {
                        Key = x.Cust_Name,
                        Value = x.Id
                    })
                    .ToListAsync();
            return result;
        }
        public async Task UserStatus(int status, Guid Id)
        {
            var userId = await MasterDb.Queryable<GMSNet_User>()
                .Where(x => x.Id == Id)
                .Select(x => x.User_Account)
                .FirstAsync();
            if (userId == UserInfo.UserId)
                throw Oops.Bah("操作人不可修改操作人账号状态");
            await MasterDb.Updateable<GMSNet_User>()
                .SetColumns(x => x.User_Status == status)
                .Where(x => x.Id == Id)
                .ExecuteCommandAsync();
        }
    }
}
